package com.beiing.tianshuai.tianshuai.mine.ui;


import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.OrderCommentImageAdapter;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.event.EventConstant;
import com.beiing.tianshuai.tianshuai.event.messages.OrderListEvent;
import com.beiing.tianshuai.tianshuai.itemtouch.DefaultItemTouchHelper;
import com.beiing.tianshuai.tianshuai.itemtouch.DefaultItemTouchHelperCallback;
import com.beiing.tianshuai.tianshuai.mine.entity.OrderCommentDataBean;
import com.beiing.tianshuai.tianshuai.mine.presenter.OrderCommentPresenter;
import com.beiing.tianshuai.tianshuai.mine.view.OrderCommentViewImpl;
import com.beiing.tianshuai.tianshuai.rx.RxBus;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.GlideImageLoader;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.tianshuai.gallerypic.config.GalleryConfig;
import com.tianshuai.gallerypic.config.GalleryPick;
import com.tianshuai.gallerypic.inter.IHandlerCallBack;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileBatchCallback;
import com.zxy.tiny.callback.FileCallback;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.beiing.tianshuai.tianshuai.app.HttpRequestConstant.USER_PIC_HEAD;
import static com.beiing.tianshuai.tianshuai.mine.ui.FeedBackActivity.PERMISSIONS_REQUEST_READ_CONTACTS;

/**
 * zh
 */
public class OrderCommentActivity extends BaseActivity implements OrderCommentViewImpl {
    /**
     * toolbar 返回按钮
     */
    @BindView(R.id.toolbar_navigation_back)
    ImageButton toolbarNavigationBack;
    /**
     * toolbar 更多按钮
     */
    @BindView(R.id.toolbar_filter_more)
    ImageButton toolbarFilterMore;
    /**
     * 货物照片
     */
    @BindView(R.id.iv_goods_photo)
    ImageView ivGoodsPhoto;
    /**
     * 货物评价 五星评价
     */
    @BindView(R.id.rb_comment)
    RatingBar rbComment;
    /**
     * 评价信息输入
     */
    @BindView(R.id.et_comment_input)
    EditText etCommentInput;
    /**
     * 卖家照片
     */
    @BindView(R.id.iv_seller_photo)
    QMUIRadiusImageView ivSellerPhoto;
    /**
     * 卖家姓名
     */
    @BindView(R.id.tv_seller_name)
    TextView tvSellerName;
    /**
     * 卖家态度五星评价
     */
    @BindView(R.id.rb_comment_seller)
    RatingBar rbCommentSeller;
    /**
     * 物流服务五星评价
     */
    @BindView(R.id.rb_comment_log)
    RatingBar rbCommentLog;
    /**
     * 匿名评价选择按钮
     */
    @BindView(R.id.tv_anonymous)
    TextView tvAnonymous;
    /**
     * 提交评价
     */
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    /**
     * 评价状态 非常好，好，一般，差，非常差
     */
    @BindView(R.id.tv_comment_state)
    TextView tvCommentState;
    /**
     * 输入状态 300字
     */
    @BindView(R.id.tv_input_number)
    TextView tvInputNumber;
    /**
     * 图片显示横向列表
     */
    @BindView(R.id.rv_comment_images_list)
    RecyclerView rvCommentImagesList;

    /**
     * toolbar 标题
     */
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;

    /**
     * 图片列表适配器
     */
    private OrderCommentImageAdapter mAdapter;
    /**
     * 是否匿名评价
     */
    private Boolean mAnonymous = true;

    private static final String TAG = "OrderCommentActivity";

    /**
     * 活动id
     */
    private String mAId;
    /**
     * 用户id
     */
    private String mFromUid;
    /**
     * 订单id
     */
    private String mOrderId;
    /**
     * 货物照片
     */
    private String mGoodsPhoto;
    /**
     * 卖家照片
     */
    private String mSellerPhoto;
    /**
     * 卖家姓名
     */
    private String mSellerName;

    /**
     * 状态标题
     */
    private String mStateTitle;

    /**
     * 主持人
     */
    private OrderCommentPresenter mPresenter;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_comment;
    }

    @Override
    protected void init() {
        initIntentExtras();
        initRecyclerView();
        initPresenter();
        initListener();

        //showShortText(mAId + " " + mFromUid + " " + mOrderId);

        toolbarTitle.setText(mStateTitle);
        //获取卖家或活动方名称
        tvSellerName.setText(mSellerName);
        //用户头像比例参数
        RequestOptions userPhotoOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .placeholder(R.mipmap.default_avatar)
                .override(50, 50);
        RequestOptions goodsPhotoOptions = new RequestOptions()
                //货物照片比例参数,按照1:1.75
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .placeholder(R.mipmap.default_avatar)
                .override(75, 75);

        //货物照片
        Glide.with(mContext.getApplicationContext())
                .load(HttpRequestConstant.ACTIVITY_PIC_HEAD + mGoodsPhoto)
                .apply(goodsPhotoOptions)
                .into(ivGoodsPhoto);
        //卖家或活动方小头像照片
        Glide.with(mContext.getApplicationContext())
                .load(USER_PIC_HEAD + mSellerPhoto)
                .apply(userPhotoOptions)
                .into(ivSellerPhoto);
    }

    /**
     * 获取传递的数据
     */
    private void initIntentExtras() {
        Intent intent = getIntent();
        mAId = intent.getStringExtra("aId");
        mFromUid = intent.getStringExtra("fromUid");
        mOrderId = intent.getStringExtra("orderId");
        mGoodsPhoto = intent.getStringExtra("goodsPhoto");
        mSellerPhoto = intent.getStringExtra("sellerPhoto");
        mSellerName = intent.getStringExtra("sellerName");
        mStateTitle=intent.getStringExtra("state");
    }

    /**
     * 开启本Activity 需要的参数
     *
     * @param context     上下文
     * @param aId         活动id
     * @param fromUid     用户id
     * @param orderId     订单id
     * @param goodsPhoto  货物照片
     * @param sellerPhoto 卖家照片
     * @param sellerName  卖家姓名
     */
    public static void start(Context context, String aId, String fromUid, String orderId, String goodsPhoto,
                             String sellerPhoto, String sellerName, String state) {
        Intent intent = new Intent(context, OrderCommentActivity.class);
        intent.putExtra("aId", aId);
        intent.putExtra("fromUid", fromUid);
        intent.putExtra("orderId", orderId);
        intent.putExtra("goodsPhoto", goodsPhoto);
        intent.putExtra("sellerPhoto", sellerPhoto);
        intent.putExtra("sellerName", sellerName);
        intent.putExtra("state", state);
        //强转返回参数,请求码
        ((Activity) context).startActivityForResult(intent, AppConstant.REQUEST_CODE_APPLY_REFRESH);
    }

    private void initRecyclerView() {
        mAdapter = new OrderCommentImageAdapter(mContext);
        rvCommentImagesList.setAdapter(mAdapter);
        //每行几个item,
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 4);
        /*
         *  设置SpanSizeLookup，它将决定view会横跨多少列。这个方法是为RecyclerView添加Header和Footer的关键。
         *  当判断position指向的View为Header或者Footer时候，返回总列数 lm.getSpanCount() ,即可让其独占一行。
         */
        rvCommentImagesList.setNestedScrollingEnabled(false);
        rvCommentImagesList.setLayoutManager(gridLayoutManager);
        //绘制item间的分割线，
        rvCommentImagesList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.set(10, 10, 10, 10);
            }
        });
        rvCommentImagesList.setItemAnimator(new DefaultItemAnimator());

        // 设置ItemTouchListener
        DefaultItemTouchHelper defaultItemTouchHelper = new DefaultItemTouchHelper(mOnItemTouchCallbackListener);
        defaultItemTouchHelper.attachToRecyclerView(rvCommentImagesList);
        defaultItemTouchHelper.setDragEnable(true);
        defaultItemTouchHelper.setSwipeEnable(false);
    }

    private void initListener() {
        // 图片点击事件
        mAdapter.setOnItemClickListener(new OrderCommentImageAdapter.OnItemClickListener() {
            @Override
            public void onImageClickListener(View view, int position) {
                int size = mAdapter.getList().size();
                if (size < 5 && position == size) {
                    checkSelfPermission();
                } else {
                    updateImage(position);
                }
            }

            @Override
            public void onImageDeleteClickListener(View view, int position) {
                mAdapter.removeData(position);
                int size = mAdapter.getList().size();
                LogUtils.i(mAdapter.getList().toString(), TAG);
            }
        });
        //是否匿名评论,状态判断,默认匿名
        tvAnonymous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Drawable drawableBlue = ContextCompat.getDrawable(mContext, R.drawable.ic_radio_on_blue);
                Drawable drawableGray = ContextCompat.getDrawable(mContext, R.drawable.ic_radio_off_gray);
                if (mAnonymous) {
                    //更改TextView中的图片
                    drawableGray.setBounds(0, 0, drawableGray.getMinimumWidth(), drawableGray.getMinimumHeight());
                    tvAnonymous.setCompoundDrawables(drawableGray, null, null, null);
                    mAnonymous = false;
                } else {
                    drawableBlue.setBounds(0, 0, drawableBlue.getMinimumWidth(), drawableBlue.getMinimumHeight());
                    tvAnonymous.setCompoundDrawables(drawableBlue, null, null, null);
                    mAnonymous = true;
                }

            }
        });
        // 内容
        etCommentInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                tvInputNumber.setText(MessageFormat.format("{0}/300", editable.length()));
            }
        });

        //货物五星评价
        rbComment.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                //showShortText(Float.toString(rating));
                switch (Float.toString(rating)) {
                    case "0.0":
                        tvCommentState.setText(" ");
                        break;
                    case "1.0":
                        tvCommentState.setText("非常差");
                        break;
                    case "2.0":
                        tvCommentState.setText("差");
                        break;
                    case "3.0":
                        tvCommentState.setText("一般");
                        break;
                    case "4.0":
                        tvCommentState.setText("好");
                        break;
                    case "5.0":
                        tvCommentState.setText("非常好");
                        break;
                    default:
                        break;
                }
            }
        });
        //物流五星评价
        rbCommentLog.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                // showShortText("物流评价" + Float.toString(rating));
            }
        });
        //卖家，活动方五星评价
        rbCommentSeller.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                // showShortText("活动方评价" + Float.toString(rating));
            }
        });
        tvSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //showShortText("提交评价");
                LogUtils.i("提交评价", "submit");

                //评价内容，后台限制1000字
                String contents = etCommentInput.getText().toString();
                //订单货物五星评价
                String orderStart = Integer.toString(rbComment.getNumStars());
                //商家星评
                String merchStar = Integer.toString(rbCommentSeller.getNumStars());
                //物流星评
                String logisticsStar = Integer.toString(rbCommentLog.getNumStars());
                //是否匿名,1为匿名，0为不匿名，默认flase 匿名
                String isAnonymous = mAnonymous ? "0" : "1";
                // 获取图片路径
                List<String> imgPaths = mAdapter.getList();

                mPresenter.setOrderComment(mAId, mFromUid, mOrderId, contents, orderStart, merchStar,
                        logisticsStar, isAnonymous, imgPaths);
            }
        });
        toolbarNavigationBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        toolbarFilterMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShortText("更多信息，敬请期待");
            }
        });
    }

    /**
     * 需要添加的数据参数
     */
    public void initPresenter() {
        mPresenter = new OrderCommentPresenter(this);
    }

    //图片替换部分
    private void updateImage(final int index) {
        List<String> path = new ArrayList<>();
        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                LogUtils.i("----------------- 选图开始 -----------------", TAG);
            }

            @Override
            public void onSuccess(List<String> photoList) {
                String filesPath = photoList.get(0);
                // 压缩图片
                Tiny.FileCompressOptions tinyOptions = new Tiny.FileCompressOptions();
                Tiny.getInstance().source(filesPath).asFile().withOptions(tinyOptions).compress(new FileCallback() {
                    @Override
                    public void callback(boolean isSuccess, String outfile) {
                        mAdapter.updateData(outfile, index);
                    }
                });
            }

            @Override
            public void onCancel() {
                LogUtils.i("用户已取消", TAG);
            }

            @Override
            public void onFinish() {
                LogUtils.i("----------------- 选图结束 -----------------", TAG);
            }

            @Override
            public void onError() {
                LogUtils.e("----------------- 选图异常 -----------------", TAG);
            }
        };
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())                // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)                 // 监听接口（必填）
                .provider("com.beiing.tianshuai.fileprovider")      // provider (必填)
                .pathList(path)                                     // 记录已选的图片
                .multiSelect(false)                                 // 是否多选   默认：false
                .crop(false)                                        // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .isShowCamera(true)                                 // 是否现实相机按钮  默认：false
                .filePath("/TianShuai/Pictures")                    // 图片存放路径
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(OrderCommentActivity.this);
    }

    //图片选择部分
    private void selectImage() {
        int maxImgNum = 5 - mAdapter.getList().size();
        List<String> path = new ArrayList<>();
        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                LogUtils.i("----------------- 选图开始 -----------------", TAG);
            }

            @Override
            public void onSuccess(List<String> photoList) {
                final String[] filesPath = photoList.toArray(new String[photoList.size()]);
                // 压缩图片
                Tiny.FileCompressOptions tinyOptions = new Tiny.FileCompressOptions();
                Tiny.getInstance().source(filesPath).batchAsFile().withOptions(tinyOptions).batchCompress(new FileBatchCallback() {
                    @Override
                    public void callback(boolean isSuccess, String[] outfile) {
                        List<String> outFiles = Arrays.asList(outfile);
                        for (int i = 0; i < outFiles.size(); i++) {
                            int size = mAdapter.getList().size();
                            if (size < 5) {
                                mAdapter.addData(size, outFiles.get(i));
                            } else {
                                //最后一个条目添加会崩溃，所以用这个方法
                                mAdapter.appendData(outFiles.get(i));
                            }
                        }
                        LogUtils.d(mAdapter.getList().toString(), TAG);
                    }
                });
            }

            @Override
            public void onCancel() {
                LogUtils.i("用户已取消", TAG);
            }

            @Override
            public void onFinish() {
                LogUtils.i("----------------- 选图结束 -----------------", TAG);
            }

            @Override
            public void onError() {
                LogUtils.e("----------------- 选图异常 -----------------", TAG);
            }
        };
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())                // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)                 // 监听接口（必填）
                .provider("com.beiing.tianshuai.fileprovider")      // provider (必填)
                .pathList(path)                                     // 记录已选的图片
                .multiSelect(true, maxImgNum)           // 是否多选   默认：false
                .crop(false)                                        // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .isShowCamera(true)                                 // 是否现实相机按钮  默认：false
                .filePath("/TianShuai/Pictures")                    // 图片存放路径
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(OrderCommentActivity.this);
    }

    //动态权限申请
    private void checkSelfPermission() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            LogUtils.i("需要授权", TAG);
            if (ActivityCompat.shouldShowRequestPermissionRationale(OrderCommentActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                LogUtils.i("拒绝过了", TAG);
                // 提示用户如果想要正常使用，要手动去设置中授权。
                showShortText("请在 设置-应用管理 中开启此应用的储存授权。");
            } else {
                LogUtils.i("进行授权", TAG);
                ActivityCompat.requestPermissions(OrderCommentActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            LogUtils.i("不需要授权", TAG);
            // 进行正常操作
            selectImage();
        }
    }

    /**
     * RecyclerView Item的触摸事件监听
     */
    private DefaultItemTouchHelperCallback.OnItemTouchCallbackListener mOnItemTouchCallbackListener = new DefaultItemTouchHelperCallback.OnItemTouchCallbackListener() {
        @Override
        public void onSwiped(int adapterPosition) {
            if (mAdapter != null) {
                mAdapter.removeData(adapterPosition);
            }
        }

        @Override
        public boolean onMove(int srcPosition, int targetPosition) {
            if (mAdapter != null) {
                // 更新UI中item的位置
                mAdapter.swapMoved(srcPosition, targetPosition);
            }
            return false;
        }
    };


    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void onRequestSuccess(OrderCommentDataBean bean) {

    }

    @Override
    public void onRequestFailed(Throwable throwable) {

    }

    /**
     * view层 提交评价成功
     *
     * @param bean 评价返回
     */
    @Override
    public void getOrderCommentSuccess(OrderCommentDataBean bean) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                showShortText("评价成功");
                //返回结果码给订单详情页
                setResult(AppConstant.RESULT_CODE_APPLY_TO_ORDER_DETAIL);

                //添加评论成功发送消息通知消息列表页更新
                RxBus.getInstanceBus().post(
                        new OrderListEvent<>(
                                EventConstant.EVENT_TYPE_UPDATE_ORDER_LIST,
                                "添加评论成功")
                );
                finish();
                //刷新，两级刷新
                break;
            case 401:
                showShortText("参数错误");
                break;
            case 202:
                showShortText("执行失败");
                break;
            default:
                break;
        }
    }

    @Override
    public void getOrderCommentError(OrderCommentDataBean bean) {
        showShortText("网络请求失败");
    }

}
